package com.syzg.base.role.dao.impl;

import com.syzg.base.merge.model.PersonRole;
import com.syzg.base.merge.model.Role;
import com.syzg.base.role.dao.RoleDAO;
import com.syzg.common.dao.impl.BaseDAOHibernate;
import com.syzg.common.util.SearchMap;
import com.syzg.common.util.SystemUtil;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.springframework.stereotype.Repository;

@Repository("roleDao")
public class RoleDAOImpl extends BaseDAOHibernate<Role>
  implements RoleDAO
{
  protected Class<Role> getEntityClass()
  {
    return Role.class;
  }

  public void deleteRoleOperationRelation(String roleId) {
    executeHql("delete from RoleOperation t where t.role.id='" + roleId + "'");
  }

  public void deleteRole(String roleId) {
    executeHql("delete from Role t where t.id='" + roleId + "'");
  }

  public List findRoles()
  {
    SearchMap searchMap = SearchMap.forClass(Role.class);
    searchMap.addOrder("a.id", (short)-1);
    return findObjects(searchMap);
  }

  public List findRolesByPerson(String personId)
  {
    String hql = "select a ,(select 'checked' from PersonRole as b where b.role.id=a.id and b.person.id=?) from Role as a";
    Query query = getSession().createQuery(hql);
    query.setParameter(0, personId);
    return query.list();
  }

  public String[] findRoleIdsByPersonId(String personId)
  {
    SearchMap searchMap = SearchMap.forClass(PersonRole.class);
    searchMap.setProjection(Projections.projectionList().add(Property.forName("a.role.id")));
    searchMap.eq("a.person.id", personId);
    List list = findObjects(searchMap);
    if ((list != null) && (list.size() > 0)) {
      String[] roleIds = new String[list.size()];
      int i = 0;
      for (Iterator iterator = list.iterator(); iterator.hasNext(); )
      {
        String roleId = (String)iterator.next();
        roleIds[(i++)] = roleId;
      }
      return roleIds;
    }
    return null;
  }

  public String[] queryRoleUsed(String[] roleIds)
  {
    String jql = "select distinct b.role.name from PersonRole b where b.role.id in (" + SystemUtil.getInSql(roleIds) + ")";
    List list = getSession().createQuery(jql).list();

    if ((list != null) && (list.size() > 0)) {
      return (String[])list.toArray(new String[list.size()]);
    }
    return null;
  }
}